package com.newworld.dmsapp2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.newworld.defect.SingleMediaScanner;
import com.newworld.dmsapp2.bean.HostAdress;
import com.newworld.dmsapp2.fragment.bean.UpdateApp;
import com.newworld.dmsapp2.ui.view.CustomDialog;
import com.newworld.dmsapp2.ui.view.MyProgressBar;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.MyPreference;
import com.newworld.dmsapp2.util.SysApplication;
import com.newworld.dmsapp2.util.Tool;
import com.pgyersdk.crash.PgyCrashManager;

public class InitAppActivity extends Activity {

	private TextView updateTv;
	private MyProgressBar updatePb;
	private CustomDialog dialog;

	/* 下载中 */
	private static final int DOWNLOAD = 1;
	/* 下载结束 */
	private static final int DOWNLOAD_FINISH = 2;
	/* 下载保存路径 */
	private String mSavePath;
	/* 记录进度条数量 */
	private int progress;
	/* 是否取消更新 */
	private boolean cancelUpdate = false;

	private Context mContext;

	// 更新版本号
	private String updateVersionCode = "5";

	// 更新版本名
	private String updateVersionName = "0.0.5beta";

	// 更新软件url
	private String updateUrl;
	// 软件名
	private String appName;

	// 是否更新本地数据库 1:更新 0：不更新
	private String updateData;

	// 最新的app版本的appKey
	private String appKey;
	
	private int updateFlag = 0;//0:不需更新 1：可更新 2：强制更新

	private UpdateApp app = new UpdateApp();

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 正在下载
			case DOWNLOAD:
				// 设置进度条位置
				updatePb.setProgress(progress);
				break;
			case DOWNLOAD_FINISH:
				// 安装文件
				installApk();
				break;
			case Config.HANDLER_MSG_GETHOSTADRESS_SUCCESS:
				// 安装文件
				Toast.makeText(InitAppActivity.this, "获取初始地址列表成功",
						Toast.LENGTH_SHORT).show();
				break;
			case Config.HANDLER_MSG_APP_DIFINE_SUCCESS:
				updateData = "0";
				UpdateApp getapp = (UpdateApp) msg.obj;
				appKey = getapp.getAppKey();
				appName = getapp.getAppFileName();
				updateVersionName = getapp.getAppVersion();
				updateVersionCode = getapp.getAppVersionNo();
				updateUrl =  Config.APP_DWONLOAD_APK + "?" + "_api_key="
						+ Config.APP_API_KEY + "&" + "aKey=" + appKey;
				checkUpdate();
				/*updateData = "0";
				UpdateApp getapp = (UpdateApp) msg.obj;
				appKey = getapp.getAppKey();
				appName = getapp.getAppFileName();
				updateVersionName = getapp.getAppVersion();
				updateVersionCode = getapp.getAppVersionNo();
				updateUrl = Config.APP_DWONLOAD_APK + "?" + "_api_key="
						+ Config.APP_API_KEY + "&" + "aKey=" + appKey;
				Bundle bundle = new Bundle();
				bundle.putString(Config.APP_UPDATEURL, updateUrl);
				showDownload();*/

				// 检查软件更新

				Toast.makeText(InitAppActivity.this, "验证app版本成功",
						Toast.LENGTH_SHORT).show();
				break;
			case Config.HANDLER_MSG_APP_DIFINE_FAIL:
				Toast.makeText(InitAppActivity.this, (String) msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_init_app);
		PgyCrashManager.register(this);
		initView();
		buildContent();
		
		/*
		 * Intent intent = new Intent(InitAppActivity.this,LoginActivity.class);
		 * startActivity(intent);
		 */
		/*
		 * startActivity(intent); new Thread(new Runnable() {
		 * 
		 * @Override public void run() throws InterruptedException { new
		 * defineApp().start(); Intent intent = new
		 * Intent(InitAppActivity.this,LoginActivity.class);
		 * startActivity(intent); } }).start();
		 */

	}

	private void initView() {
		updateTv = (TextView) findViewById(R.id.initapp_update_text);
		updatePb = (MyProgressBar) findViewById(R.id.initapp_update_progress);
		updateTv.setVisibility(View.INVISIBLE);
		updatePb.setVisibility(View.INVISIBLE);
		new defineApp().start();
		//checkUpdate();
		// 标准的对话框封装
		/*
		 * dialog = new CustomDialog(InitAppActivity.this);
		 * dialog.setTitle("版本更新信息"); dialog.setDetial("必须更新版本，才能开启软件");
		 * dialog.setLeftOnClick(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { dialog.dismiss(); // 关闭整个程序
		 * SysApplication.getInstance().exit(); } }); dialog.show();
		 * dialog.setRightOnClick(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { dialog.dismiss();
		 * updateTv.setVisibility(View.VISIBLE);
		 * updatePb.setVisibility(View.VISIBLE); new defineApp().start();
		 * 
		 * } }); dialog.show();
		 */
	}

	// 验证App短链接

	class defineApp extends Thread {
		public HashMap<String, String> orderList;
		public HashMap<String, String> searchList;
		public String curPage;
		public String search = "";

		public defineApp() {
			super();

		}

		@Override
		public void run() {

			if (Tool.isNetworkAvailable(InitAppActivity.this)) {
				try {
					String url = Config.APP_DEFINE_URL;
					Map<String, String> map = new HashMap<String, String>();
					map.put("shortcut", Config.APP_SHORT_CUT);
					map.put("_api_key", Config.APP_API_KEY);
					String result = null;
					result = HttpUtil.postRequest(url, map);
					result = result.replace("rows", "tasks");
					Log.e("我访问的url是：", url);
					Log.e("我访问shortcut的是：", map.get("shortcut"));
					Log.e("我访问_api_key的是：", map.get("_api_key"));
					Log.e("搜索的result", result);
					JSONObject resulObj = new JSONObject(result);
					String code = resulObj.getString("code");
					String message = resulObj.getString("message");
					String data = resulObj.getString("data");
					if (code.equals("0")) {// 短链接成功
						java.lang.reflect.Type type = new TypeToken<UpdateApp>() {
						}.getType();
						Gson gson = new Gson();
						app = gson.fromJson(data, type);
						mHandler.obtainMessage(
								Config.HANDLER_MSG_APP_DIFINE_SUCCESS, app)
								.sendToTarget();
					} else if (code.equals("2")) {// 短链接失败
						mHandler.obtainMessage(
								Config.HANDLER_MSG_APP_DIFINE_FAIL, message)
								.sendToTarget();
					} else {
						mHandler.obtainMessage(
								Config.HANDLER_MSG_APP_DIFINE_FAIL, message)
								.sendToTarget();
					}

				} catch (Exception e) {

					Log.e("SettingSoftwareVersionActivity", "defineApp 网络连接问题");
					
					e.printStackTrace();
				}
			} else {
				// handler.sendEmptyMessage(1);
			}

		}

	}

	/**
	 * 检测软件更新
	 */
	public void checkUpdate() {
 
		if (isUpdate() == 2) {
			Log.e("版本更新", "更新版本号必强制更新");
			// 标准的对话框封装
			dialog = new CustomDialog(InitAppActivity.this);
			dialog.setTitle("版本更新信息");
			dialog.setDetial("必须更新版本，才能开启软件");
			dialog.setLeftOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					
					Toast.makeText(InitAppActivity.this, "取消更新，将无法使用软件", Toast.LENGTH_SHORT).show();
				}
			});
			dialog.show();
			dialog.setRightOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.e("版本更新", "选择强制更新");
					dialog.dismiss();
					updateTv.setVisibility(View.VISIBLE);
					updatePb.setVisibility(View.VISIBLE);
					
					Bundle bundle = new Bundle();
					bundle.putString(Config.APP_UPDATEURL, updateUrl);
					showDownload();

				}
			});
			dialog.show();
		}else if (isUpdate() == 1) {
			Log.e("版本更新", "更新版本号不必强制更新");
			// 标准的对话框封装
			dialog = new CustomDialog(InitAppActivity.this);
			dialog.setTitle("版本更新信息");
			dialog.setDetial("有新的版本可更新，现在更新嘛？");
			dialog.setLeftOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
					// 关闭整个程序
					// SysApplication.getInstance().exit();
					Intent intent = new Intent(InitAppActivity.this,
							InitActivity.class);
					startActivity(intent);
				}
			});
			dialog.show();
			dialog.setRightOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.e("版本更新", "选择更新");
					dialog.dismiss();
					updateTv.setVisibility(View.VISIBLE);
					updatePb.setVisibility(View.VISIBLE);
					
					Bundle bundle = new Bundle();
					bundle.putString(Config.APP_UPDATEURL, updateUrl);
					showDownload();

				}
			});
			dialog.show();
		}else {
			Log.e("版本更新", "更新版本号更新");
			Intent intent = new Intent(InitAppActivity.this, InitActivity.class);
			startActivity(intent);
		}

	}

	/**
	 * 检查软件是否有更新版本
	 * 
	 * @return
	 */
	private int isUpdate() {
		// 获取当前软件版本
		int versionCode = 0;
		String versionName = "";
		// String[] versionNameStr = new String[3];
		try {
			versionCode = getVersionCode();
			versionName = getVersionName();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		int serviceCode = Integer.valueOf(updateVersionCode);
		// 版本判断
		if (serviceCode > versionCode) {
			String[] versionNameStr = versionName.split("\\.");
			String[] updateVersionNameStr = updateVersionName.split("\\.");
			if (Integer.parseInt(updateVersionNameStr[0]) > Integer
					.parseInt(versionNameStr[0])
					|| Integer.parseInt(updateVersionNameStr[1]) > Integer
							.parseInt(versionNameStr[1])) {
				updateFlag = 2;
				Log.e("版本比较", "更新版本号必须强制更新");
			} else {
				Log.e("版本比较", "更新版本号不必强制更新");
				updateFlag = 1;
			}
		} else {
			Log.e("版本比较", "更新版本号不大");
			updateFlag = 0;
		}
		return updateFlag;
	}

	/**
	 * 检查软件是否有更新版本
	 * 
	 * @return
	 */
	@SuppressWarnings("unused")
	private void isUpdateData() {
		if (updateData.equals("1")) {
			deleteData();
			deleteFilesByDirectory(new File(Config.IMAGE_PATH));
			deleteFilesByDirectory(new File(Config.VOICE_PATH));
		}
	}

	/*
	 * 删除本地数据库
	 */
	private void deleteData() {
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.User.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.Function.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.Photo.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.Task.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.RelationHouse.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.RepairApply.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.RepairNode.class);
		DataSupport.deleteAll(com.newworld.dmsapp2.bean.Server.class);
	}

	// 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理 * * @param directory
	@SuppressLint("NewApi")
	public void deleteFilesByDirectory(File directory) {
		if (directory != null && directory.exists() && directory.isDirectory()) {
			for (File item : directory.listFiles()) {
				System.out.println("item.getAbsolutePath()>>>>>"
						+ item.getAbsolutePath());
				String fileName = item.getName();
				System.out.println(fileName);
				item.delete();
				String filePath = directory + fileName;
				MediaScannerConnection.scanFile(mContext,
						new String[] { directory + fileName }, null, null);
				File dbFile = new File(filePath);
				new SingleMediaScanner(mContext, dbFile);
			}
		}
	}

	/**
	 * 获取软件版本号
	 * 
	 * @param context
	 * @return
	 */
	private int getVersionCode() throws Exception {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
				0);
		int version = packInfo.versionCode;
		return version;
	}

	// 获取软件当前版本号
	private String getVersionName() throws Exception {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
				0);
		String version = packInfo.versionName;
		return version;
	}

	/**
	 * 显示软件下载对话框
	 */
	private void showDownload() {
		// 给下载对话框增加进度条
		// 现在文件
		downloadApk();
	}

	/**
	 * 下载apk文件
	 */
	private void downloadApk() {
		// 启动新线程下载软件
		new downloadApkThread().start();
	}

	/**
	 * 下载文件线程
	 * 
	 * @author coolszy
	 * @date 2012-4-26
	 * @blog http://blog.92coding.com
	 */
	private class downloadApkThread extends Thread {
		@Override
		public void run() {
			try {
				// 判断SD卡是否存在，并且是否具有读写权限
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					// 获得存储卡的路径
					String sdpath = Environment.getExternalStorageDirectory()
							+ "/";
					mSavePath = sdpath + "download";
					URL url = new URL(updateUrl);
					// 创建连接
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.connect();
					// 获取文件大小
					int length = conn.getContentLength();
					// 创建输入流
					InputStream is = conn.getInputStream();

					File file = new File(mSavePath);
					// 判断文件目录是否存在
					if (!file.exists()) {
						file.mkdir();
					}
					File apkFile = new File(mSavePath, appName);
					FileOutputStream fos = new FileOutputStream(apkFile);
					int count = 0;
					// 缓存
					byte buf[] = new byte[1024];
					// 写入到文件中
					do {
						int numread = is.read(buf);
						count += numread;
						// 计算进度条位置
						progress = (int) (((float) count / length) * 100);
						// 更新进度
						mHandler.sendEmptyMessage(DOWNLOAD);
						if (numread <= 0) {
							// 下载完成
							mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
							break;
						}
						// 写入文件
						fos.write(buf, 0, numread);
					} while (!cancelUpdate);// 点击取消就停止下载.
					fos.close();
					is.close();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 取消下载对话框显示
		}
	};

	/**
	 * 安装APK文件
	 */
	private void installApk() {
		File apkfile = new File(mSavePath, appName);
		if (!apkfile.exists()) {
			return;
		}
		// 通过Intent安装APK文件
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		startActivity(i);
	}

	@Override
	protected void onStop() {
		super.onStop();
		this.finish();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// JPushInterface.onResume(this);
		// MobclickAgent.onResume(this);

	}

	@Override
	protected void onPause() {
		super.onPause();
		// JPushInterface.onPause(this);
		// MobclickAgent.onPause(this);

	}

	/**
	 * 监听Back键按下事件,方法2: 注意: 返回值表示:是否能完全处理该事件 在此处返回false,所以会继续传播该事件.
	 * 在具体项目中此处的返回值视情况而定.
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			// 关闭整个程序
			SysApplication.getInstance().exit();

			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	}

	/*Runnable getHostIps = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {

				String result = HttpUtil.getRequest(Config.GETHOST_URL);
				JSONObject jsonobj = new JSONObject(result);
				//String message = jsonobj.getString("message");
				if (jsonobj.getString("flag").equals("success")) {
					DataSupport.deleteAll(HostAdress.class);
					String rows = jsonobj.getString("obj");
					// String mainHostAddress =
					// jsonobj.getString("mainHostAddress");
					java.lang.reflect.Type type = new TypeToken<HostAdress>() {
					}.getType();
					Gson gson = new Gson();
					HostAdress hostAdress = gson.fromJson(rows, type);
					hostAdress.save();
					if (null != hostAdress.getUpdateHostAddress()
							&& !hostAdress.getUpdateHostAddress().isEmpty()) {
						MyPreference.getInstance(InitAppActivity.this)
								.setUpdateUrl(
										hostAdress.getUpdateHostAddress()
												.get(0).getValue());
					}
					if (null != hostAdress.getMessageHostAddress()
							&& !hostAdress.getMessageHostAddress().isEmpty()) {
						MyPreference.getInstance(InitAppActivity.this)
								.setMessageUrl(
										hostAdress.getMessageHostAddress()
												.get(0).getValue());
					}

					// JSONArray jsonArray = new JSONArray(mainHostAddress);
					
					 * for (Url u:HostAdress.getMainHostAddress()) {
					 * 
					 * hostIps.add(u.getValue()); Log.e("android访问主机地址",
					 * u.getName()+u.getValue());
					 * 
					 * } for (Url u:HostAdress.getUpdateHostAddress()) {
					 * hostIps.add(u.getValue()); Log.e("android访问主机地址",
					 * u.getName()+u.getValue()); }
					 
					mHandler.obtainMessage(
							Config.HANDLER_MSG_GETHOSTADRESS_SUCCESS)
							.sendToTarget();// 通知主线程数据发送成功
				} else {
					// progressBarHandler.obtainMessage(2,
					// hostIps).sendToTarget();
				}

			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				// progressBarHandler.obtainMessage(2, hostIps).sendToTarget();
			}

		}
	};*/
	Runnable getAppUpdateRule = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {

				String result = HttpUtil.getRequest(Tool.getConfigUrl(Config.SERVER_URL, Config.GETHOST_URL));
				JSONObject jsonobj = new JSONObject(result);
				//String message = jsonobj.getString("message");
				if (jsonobj.getString("flag").equals("success")) {
					String rows = jsonobj.getString("obj");
					List<HostAdress> hs = DataSupport.findAll(HostAdress.class);
					HostAdress h = hs.get(0);
					// String mainHostAddress =
					// jsonobj.getString("mainHostAddress");
					java.lang.reflect.Type type = new TypeToken<HostAdress>() {
					}.getType();
					Gson gson = new Gson();
					HostAdress hostAdress = gson.fromJson(rows, type);
					h.setPhoneBaseFunction(hostAdress.getPhoneBaseFunction());
					h.update(h.getId());
					mHandler.obtainMessage(
							Config.HANDLER_MSG_GETHOSTADRESS_SUCCESS)
							.sendToTarget();// 通知主线程数据发送成功
				} else {
					// progressBarHandler.obtainMessage(2,
					// hostIps).sendToTarget();
				}

			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				// progressBarHandler.obtainMessage(2, hostIps).sendToTarget();
			}

		}
	};
	
	//创建文件夹
			private void buildContent(){
				File downdestDir = new File(Environment
						.getExternalStorageDirectory().getPath()
						+ File.separator
						+ "NewWorld_APP2_AvatarImage");
				  if (!downdestDir.exists()) {
					  downdestDir.mkdirs();
				  }
				File imagedestDir = new File(Environment
						.getExternalStorageDirectory().getPath()
						+ File.separator
						+ "NewWorld_APP2_Photo");
				  if (!imagedestDir.exists()) {
					  imagedestDir.mkdirs();
				  }

				  File voicedestDir = new File(Environment
							.getExternalStorageDirectory().getPath()
							+ File.separator
							+ "NewWorld_APP2_Voice");
				  if (!voicedestDir.exists()) {
					  voicedestDir.mkdirs();
				  }

				  File txtdestDir = new File(Environment
							.getExternalStorageDirectory().getPath()
							+ File.separator
							+ "NewWorld_APP2_Software");
				  if (!txtdestDir.exists()) {
					  txtdestDir.mkdirs();
				  }

			}
}
